package com.atguigu.chapter05.transform;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/16 15:15
 */
public class Flink08_Reduce {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        DataStreamSource<WaterSensor> s1 = env.fromElements(
            new WaterSensor("sensor_1", 1L, 10),
            new WaterSensor("sensor_1", 4L, 40),
            new WaterSensor("sensor_2", 3L, 30)
//            new WaterSensor("sensor_1", 2L, 40),
//            new WaterSensor("sensor_1", 5L, 50)
        );
    
        s1
            //            .keyBy(value -> value.getId())
            .keyBy(WaterSensor::getId)  // 方法引用
            .reduce(new ReduceFunction<WaterSensor>() {
                @Override
                public WaterSensor reduce(WaterSensor value1,  // 上次聚合的结果
                                          WaterSensor value2) throws Exception {
                    System.out.println("Flink08_Reduce.reduce");
                    value2.setVc(value1.getVc() + value2.getVc());
                    return value2;
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*
聚合算子:
    必须在keyBy之后使用


sum, max, min
    非聚合和分组字段默认选的是碰到的第一个值
    
 maxBy, minBy
     非聚合和分组字段 是最终最大值或最小值
     默认情况: 如果最大值相等, 其他字段取第一个
     
     
 reduce:
 1. 聚合结果的类型与输入类型保持一致
 2. 如果某个key的第一个元素来的时候, 不会触发reduce函数
 
 
 
 */